package com.soft863.tc.producer.bean;

import com.soft863.tc.common.bean.DataIn;
import com.soft863.tc.common.bean.DataOut;
import com.soft863.tc.common.bean.Producer;
import com.soft863.tc.common.util.DateUtil;
import com.soft863.tc.common.util.NumberUtil;

import java.io.IOException;
import java.util.List;
import java.util.Random;

/*
 * 本地数据文件生产者
 * */
public class LocalFileProducer implements Producer {
    private DataIn in;
    private DataOut out;
    private volatile boolean flag = true;

    @Override
    public void setIn(DataIn in) {
        this.in = in;
    }

    @Override
    public void setOut(DataOut out) {
        this.out = out;
    }

    /*
     * 生产数据
     * */
    @Override
    public void producer() {
        //读取通讯录数据
        try {
            List<Contact> contacts = in.read(Contact.class);
            while (flag) {
                //从通讯录随机查找两个电话号码(主叫，被叫)
                int callingIndex = new Random().nextInt(contacts.size());
                int calledIndex;
                do {
                    calledIndex = new Random().nextInt(contacts.size());
                } while (callingIndex == calledIndex);
                Contact calling = contacts.get(callingIndex);
                Contact called = contacts.get(calledIndex);
                //生成随机的通话时间[2018-01-01 00:00:00 ~ 2018-12-31 00:00:00]
                long startTime = DateUtil.parse("20180101 00:00:00", "yyyyMMdd HH:mm:ss").getTime();
                long endTime = DateUtil.parse("20181231 00:00:00", "yyyyMMdd HH:mm:ss").getTime();
                long callTime = (long) (startTime + (endTime - startTime) * Math.random());
                String callTimeStr = DateUtil.format(callTime, "yyyyMMdd HH:mm:ss");
                //生成随机的通话时长
                //0189
                //1010
                //0001
                String duration = NumberUtil.format(new Random().nextInt(3600), 4);

                //生成通话记录
                CallLog log = new CallLog(calling.getTel(), called.getTel(), callTimeStr, duration);
                //将通话记录刷写到数据文件中
                out.write(log);
                System.out.println(log);
                Thread.sleep(100);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }


    }

    /*
     * 关闭生产者
     * */
    @Override
    public void close() throws IOException {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}
